package com.cy.bean;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public  class  CodeTool {

    private String token = "";

    private String code = "";

    private int state = 0;

    private static Map<String, CodeTool> codeToolMap;

    public CodeTool() {
    }

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    //初始化code
    public void refreshCode(String phone){

        synchronized (CodeTool.class){
            if (codeToolMap == null || codeToolMap.get(phone)==null){
                if(!(code.equals(""))){
                    code = "";
                }
            }else {
                if (codeToolMap.get(phone).getState()!=0){
                    code = "";
                    codeToolMap.get(phone).setState(0);
                }
                System.out.println("手机号重复申请");
            }
        }
    }

    //生成随机验证码
    public synchronized String getCode() {
        if(code.equals("")){
            Random random = new Random();
            while (code.length() < 4){
                code += random.nextInt(10);
            }
        }
        return code;
    }

    public static Map<String, CodeTool> getCodeToolMap() {
        if (codeToolMap==null){
            synchronized (CodeTool.class){
                codeToolMap = new HashMap<>();
            }
        }
        return codeToolMap;
    }

    public static void setCodeToolMap(Map<String, CodeTool> codeToolMap) {
        CodeTool.codeToolMap = codeToolMap;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}
